import React, { useEffect, useState } from 'react';
import { Button, Drawer, message, Select, Space } from 'antd';
import { TjChart } from '@/pages/ETrade/components';
import LogModal from '../LogModal';
import { PageLoading } from '@/components';
import styles from './index.less';
import { getAiTacticsByStationIdAndMarkDate, queryForecastAndAiTactics } from '../../service';
import { HttpCode } from '#/utils/contacts';
import { getBaseKeys, getXAxisData, powerAdjustBaseOptions } from '../../helper';
import { TRDefault } from '#/components';
import { TIME_96 } from '@/pages/ETrade/components/helper';
import { connect } from 'umi';
import { havePermissions } from '@/pages/ETrade/ShorttermForecastingRedesign/tool';

const OpenAiModal = (props) => {
  const {
    visible,
    onCancel,
    searchForm,
    quoteStationId,
    dispatch,
    saveButtonDisabled,
    buttonPermissions,
  } = props;

  const [aiList, setAiList] = useState([]);

  const [loading, setLoading] = useState(true);

  const [selectData, setSelectData] = useState(null);

  const [chartOptions, setChartOptions] = useState({});

  const [tableList, setTableList] = useState([]);

  const [logVisible, setLogVisible] = useState(false);

  const _onCancel = () => {
    onCancel?.();
  };

  // 获取AI策略图表数据
  const getAiData = async (algorithm = null) => {
    setLoading(true);
    const res = await queryForecastAndAiTactics({
      marketId: searchForm.marketId,
      markDate: searchForm.calendarDate,
      stationId: searchForm.stationId,
      saveType: searchForm.saveType,
      ...{ ...(algorithm ? { algorithm } : null) },
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const data = res?.data || {};
      setTableList(data?.dataList || []);
      if (Object.keys(data)?.length !== 0) {
        const keys = getBaseKeys(data);
        const series = keys.map((k) => {
          const arr = data?.[k + 'Values'] || [];
          const name = data?.[k + 'Source'];
          const color = data?.[k + 'Colour'];
          return {
            data: arr,
            type: 'line',
            name,
            color,
          };
        });
        setChartOptions({
          ...powerAdjustBaseOptions,
          xAxis: [
            {
              type: 'category',
              data: getXAxisData(searchForm?.calendarDate, data.xAxis),
            },
          ],
          series,
        });
      } else {
        setChartOptions({});
      }
    } else {
      setChartOptions({});
      message.error(res?.message || '获取AI策略图表数据失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    if (visible) {
      (async () => {
        // 获取AI算法列表
        const res = await getAiTacticsByStationIdAndMarkDate({
          marketId: searchForm.marketId,
          markDate: searchForm.calendarDate,
          stationId: searchForm.stationId,
        });
        if (res && res.statusCode === HttpCode.SUCCESS) {
          setAiList(res?.data || []);
        } else {
          message.error(res?.message || '获取算法列表失败');
        }
        // 获取AI策略图表数据
        await getAiData(selectData);
      })();
    }
  }, [visible]);

  const changeLogVisible = () => {
    setLogVisible(!logVisible);
  };

  const handleSave = async () => {
    if (selectData) {
      const result = havePermissions('IteraShortTermForcastSaveButtton', buttonPermissions);
      if (result) {
        const dataList = tableList.map((i) => ({
          ...i,
          timeSlot: TIME_96[i.beginIndex] + '-' + TIME_96[i.endIndex],
        }));
        dispatch({
          type: 'shortTermForecastingRedesignV2/saveAdjustTableData',
          payload: {
            dataFrom: aiList.find((i) => i.value === selectData)?.id,
            dataList: dataList,
            markDate: searchForm?.calendarDate,
            quoteStationId: quoteStationId ?? null,
            stationId: Number(searchForm?.stationId),
            marketId: searchForm.marketId,
            store: 0,
            saveType: searchForm.saveType,
          },
        });
        _onCancel();
      }
    } else {
      message.error('请选择算法');
    }
  };

  return (
    <Drawer
      destroyOnClose={true}
      width={'80vw'}
      visible={visible}
      onClose={_onCancel}
      title={
        <div className={styles.titleDiv}>
          <span className={styles.title}>
            交易操作台 / 省内现货申报 / <span style={{ color: 'var(--font)' }}>{'AI策略'}</span>
          </span>
        </div>
      }
      footer={null}
    >
      <div className={styles.body}>
        <div className={styles.head}>
          <Space>
            <div className={styles.headTitle}>AI策略</div>
            <Button type="link" onClick={changeLogVisible}>
              操作日志
            </Button>
          </Space>
          <Space>
            <Select
              placeholder="请选择算法"
              options={aiList}
              style={{ width: 240 }}
              value={selectData}
              allowClear={true}
              onChange={async (value) => {
                setSelectData(value);
                await getAiData(value);
              }}
            />
            <Button type={'primary'} onClick={handleSave} disabled={saveButtonDisabled}>
              保存
            </Button>
          </Space>
        </div>
        {loading ? (
          <PageLoading />
        ) : Object.keys(chartOptions).length === 0 ? (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        ) : (
          <div className={styles.chart}>
            <TjChart option={chartOptions} group={'D'} />
          </div>
        )}
      </div>
      <LogModal visible={logVisible} onCancel={changeLogVisible} type={1} />
    </Drawer>
  );
};

export default connect(({ shortTermForecastingRedesignV2, global }) => ({
  searchForm: shortTermForecastingRedesignV2.searchForm,
  smoothStatus: shortTermForecastingRedesignV2.smoothStatus,
  quoteStationId: shortTermForecastingRedesignV2.quoteStationId,
  saveButtonDisabled: shortTermForecastingRedesignV2.saveButtonDisabled,
  buttonPermissions: global.configure.buttonPermissions,
}))(OpenAiModal);
